package com.meng.android.component;

import java.util.Calendar;
import java.util.HashMap;

import android.annotation.TargetApi;
import android.app.DatePickerDialog;
import android.app.DatePickerDialog.OnDateSetListener;
import android.content.Context;
import android.os.Build;
import android.text.format.DateFormat;
import android.util.AttributeSet;
import android.view.View;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.meng.android.util.R;
import com.meng.android.util.UIUtils;

public class RowTextTextDate extends LinearLayout implements BindingForm,
		OnDateSetListener {

	EditText mEditText;
	TextView mTextView;
	ImageView mButton;
	Calendar mDate = Calendar.getInstance();
	private String[] bindingElement;

	public RowTextTextDate(Context context) {
		super(context);
	}

	public RowTextTextDate(Context context, AttributeSet attrs) {
		super(context, attrs);
	}

	@TargetApi(Build.VERSION_CODES.HONEYCOMB)
	public RowTextTextDate(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
	}

	@Override
	public void onDateSet(DatePicker view, int year, int monthOfYear,
			int dayOfMonth) {
		mDate.set(year, monthOfYear, dayOfMonth);
		mTextView.setText(DateFormat.getDateFormat(getContext()).format(
				mDate.getTime()));
	}

	public Calendar getDate() {
		return mDate;
	}

	public void setDate(Calendar mDate) {
		this.mDate = mDate;
	}

	public static RowTextTextDate create(final Context context, String hint) {
		final RowTextTextDate result = (RowTextTextDate) UIUtils.inflater(
				context).inflate(R.layout.row_text_text_date, null);
		result.mEditText = (EditText) result.findViewById(R.id.row_edit_text);
		result.mTextView = (TextView) result.findViewById(R.id.row_text);
		result.mButton = (ImageView) result.findViewById(R.id.row_button);
		result.mEditText.setHint(hint);
		result.mButton.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				final Calendar calendar = result.getDate();
				new DatePickerDialog(context, result, calendar
						.get(Calendar.YEAR), calendar.get(Calendar.MONTH),
						calendar.get(Calendar.DAY_OF_MONTH)).show();
			}
		});
		return result;
	}

	@Override
	public void setBindingData(String[] strings) {
		this.bindingElement = strings;
	}

	@Override
	public HashMap<String, Object> getData() {
		HashMap<String, Object> result = new HashMap<String, Object>();
		for (int i = 0; i < bindingElement.length; i++) {
			final String key = bindingElement[i];
			if (i == 0) {
				result.put(key, mEditText.getText().toString());
			} else if (i == 1) {
				result.put(key, mTextView.getText().toString());
			}
		}
		return result;
	}

	@Override
	public void updateData(HashMap<String, Object> args) {
	}

}